package com.cl.code.generate.source.controller.entity;

import com.cl.code.generate.util.JavaCommentExtractor;
import com.cl.code.generate.util.JavaCommentExtractor.ClassCommentInfo;
import lombok.Getter;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import java.lang.reflect.Method;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Stream;

/**
 * @author chengliang
 * @since 1.0.0
 */
public class ControllerMetadata {

    @Getter
    private final Class<?> controllerClass;

    @Getter
    private final String basePath;

    @Getter
    private final String comment;

    @Getter
    private final String author;

    @Getter
    private List<MethodMetadata> methods;

    public ControllerMetadata(Class<?> controllerClass) {
        this.controllerClass = controllerClass;
        if (controllerClass.isAnnotationPresent(RequestMapping.class)) {
            RequestMapping requestMapping = controllerClass.getAnnotation(RequestMapping.class);
            if (requestMapping != null && requestMapping.value().length > 0) {
                this.basePath = requestMapping.value()[0];
            } else {
                this.basePath = "";
            }
        } else {
            this.basePath = "";
        }
        ClassCommentInfo classCommentInfo = JavaCommentExtractor.extractClassCommentInfo(controllerClass);
        this.comment = classCommentInfo.getComment();
        this.author = classCommentInfo.getTag("author");
        Method[] methodsArray = controllerClass.getMethods();
        Set<Class<?>> classCacheSet = new HashSet<>();
        this.methods = Stream.of(methodsArray)
                .filter(method -> method.isAnnotationPresent(PostMapping.class))
                .map(method -> new MethodMetadata(method, basePath, classCacheSet))
                .toList();
    }

}
